from optparse import OptionParser
import logging
from ConfigParser import ConfigParser
import redis
import hashlib
import json

class ErrorCollector(object):
  def __init__(self, config_fname):
    self._load_config(config_fname)
    self._redis_cli = redis.StrictRedis(**self._redis_config)

  def _load_config(self, config_fname):
    parser = ConfigParser()
    parser.read(config_fname)
    self._redis_config = {}
    for option in parser.options('ec'):
      self._redis_config[option] = parser.get('ec', option)

  def collectError(self, redis_key, source, err, id):
    if source is None or err is None or id is None \
      or len(source) == 0 or len(err) == 0 or len(id) == 0:
      return False, None
    json_data = {}
    json_data['source'] = source
    json_data['err']    = err
    json_data['id']     = id
    try:
      result = self._redis_cli.sadd(redis_key, json_data)
    except Exception, e:
      logging.error('failed to store message : %s, reason : %s' % (str(json_data), e))
      return False, None
    else:
      return True, result

def main(config_fname, args):
  client =  ErrorCollector(config_fname)
  client.collectError('err:parseerr', 'qq', '123', '123')

if __name__ == "__main__":
  logging.basicConfig(level=logging.DEBUG,
                      format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                      datefmt='%a, %d %b %Y %H:%M:%S',
                      filename='error_collector.log',
                      filemode='w')

  parser = OptionParser()
  parser.add_option("-c", "--config", dest = "config_fname", default="config/redis.config",
                    help = "config file name")
  (options, args) = parser.parse_args()
  main(options.config_fname, args)
